import { defineStore } from "pinia";
import { ref } from "vue";
import {
  type BaseResponseUserVO,
  UserControllerService,
} from "../../generated";
import USER_ROLE_ENUM from "../access/userRoleEnum.ts";
import { ElMessage } from "element-plus";

export const useUserStore = defineStore("user", () => {

  const id = ref<number>(0);
  const userRole = ref<string>('');
  const userName = ref<string>("");
  const userAvatar = ref<string>("");
  const userAccount = ref<string>("");
  const managedClubId = ref<number>(0);
  const phoneNumber = ref<string>("");
  const major = ref<string>("");
  const grade = ref<string>("");
  const userClass = ref<string>("");

  const updateUserState = (data: BaseResponseUserVO["data"]) => {
    if (!data) return;
    id.value = data.id || 0;
    userRole.value = getUserRole(data.userRole as string);
    userName.value = data.userName || "";
    userAvatar.value = data.userAvatar || "";
    userAccount.value = data.userAccount || "";
    managedClubId.value = data.managedClubId || 0;
    phoneNumber.value = data.phoneNumber || "";
    major.value = data.major || "";
    grade.value = data.grade || "";
    userClass.value = data.userClass || "";
  };

  // 获取用户信息的方法
  const fetchUserInfo = async () => {
    const res = await UserControllerService.getLoginUser();
    if (res.code === 0 && res.data) {
      updateUserState(res.data);
    } else {
      resetUserState();
    }
  };

  // 登录方法
  const login = async (user: BaseResponseUserVO | null) => {
    if (user && user.data) {
      updateUserState(user.data);
    } else {
      await fetchUserInfo();
    }
  };

  const logout = async () => {
    try {
      const res = await UserControllerService.userLogout();
      if (res.code === 0) {
        resetUserState();
        // 清除Session Cookie
        document.cookie =
            "SESSION_ID=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
      } else {
        ElMessage.error("登出失败：" + res.message);
      }
    } catch (error) {
      console.error("登出异常:", error);
    }
  };

  // 根据userRole分配 USER_ROLE_ENUM
  const getUserRole = (userRole: string) => {
    switch (userRole) {
      case USER_ROLE_ENUM.USER:
        return USER_ROLE_ENUM.USER;
      case USER_ROLE_ENUM.ADMIN:
        return USER_ROLE_ENUM.ADMIN;
      case USER_ROLE_ENUM.MANAGER:
        return USER_ROLE_ENUM.MANAGER;
      default:
        return USER_ROLE_ENUM.NOT_LOGIN;
    }
  };

  const resetUserState = () => {
    id.value = 0;
    userRole.value = USER_ROLE_ENUM.NOT_LOGIN;
    userName.value = "";
    userAvatar.value = "";
    userAccount.value = "";
    managedClubId.value = 0;
    phoneNumber.value = "";
    major.value = "";
    grade.value = "";
    userClass.value = "";
  };

  const setUserAvatar = (avatarUrl: string) => {
    userAvatar.value = avatarUrl;
  };

  // 保留开发环境模拟登录
  const mockAdminLogin = () => {
    if (import.meta.env.MODE === "development") {
      id.value = 1;
      userRole.value = USER_ROLE_ENUM.ADMIN;
      userName.value = "管理员";
      document.cookie = `MOCK_SESSION=admin; Path=/; Max-Age=86400`;
    }
  };

  // 返回 store 的公共属性和方法
  return {
    id,
    userRole,
    userName,
    userAvatar,
    userAccount,
    managedClubId,
    phoneNumber,
    major,
    grade,
    userClass,
    login,
    logout,
    fetchUserInfo,
    mockAdminLogin,
    getUserRole,
    resetUserState,
    setUserAvatar,
    updateUserState,
  };
});
